import React, { useState, useCallback, useMemo, ReactNode, useRef, useEffect } from 'react'
import { EditStatus } from 'gantd'
import LoupeSelect from '@/components/form/loupeselect'
import { fetchUIListApi } from './service'
import { commonText } from '@/utils/utils'
import { searchSchema, gridSchema } from './schema'

const searchUISchema = {
  "ui:col": 12,
  "ui:labelCol": {},
  "ui:wrapperCol": {}
}

export interface UISelectorProps {
  bizType: string
  entryId: string
  funcType: string
  activeStatus: string
  uiType: string
  value: string
  onChange: (res: any) => void
  title?: string | ReactNode
  inGrid?: boolean
  onBlur?: Function
  labelProp: string
  [key: string]: any
}

const ITEM_STATE = {
  width: 800,
  height: 600
}

/**
 * UI选择器
 */
export default (props: UISelectorProps) => {
  const {
    bizType,
    entryId,
    uiType,
    funcType = 'ONE_DIMENSION',
    activeStatus = 'PUBLISHED',
    value,
    onChange,
    title = tr('选择UI'),
    inGrid = false,
    onBlur,
    labelProp = 'title',
    valueProp = 'name',
    ...res
  } = props

  const [currentValue, setValue] = useState(value)
  const filterInfoRef = useRef({ bizType, entryId, uiType, funcType, activeStatus })
  const [pageInfo, setPageInfo] = useState({
    pageSize: 50,
    beginIndex: 0
  })
  const pageInfoRef = useRef(pageInfo)
  const [tableLoading, setTableLoading] = useState(false)
  const [dataSource, setDataSource] = useState<any[]>([])
  const [total, setTotal] = useState(0)

  const onChange_ = useCallback((value) => {
    let res = value
    setValue(value)
    if (inGrid) {
      res = dataSource.find(item => item[valueProp] === value)
    }
    onChange && onChange(res)
    setTimeout(() => {
      onBlur && onBlur()
    }, 0)
  }, [dataSource, inGrid, onChange, onBlur, valueProp])

  const queryBySelect = useCallback(async (keywords) => {
    const params: any = {
      pageInfo: { beginIndex: 0, pageSize: 20 },
      filterInfo: { bizType, entryId, uiType, funcType, activeStatus }
    }
    if (keywords) {
      params.filterInfo = {
        ...params.filterInfo,
        entryTitle: keywords
      }
    }
    let data = []
    try {
      const res = await fetchUIListApi(params)
      data = res.content || []
    } catch (error) {

    }
    return data.map((item: any) => ({ ...item, id: String(item.id) }))
  }, [bizType, entryId, uiType, funcType, activeStatus])

  const fetch = useCallback(async () => {
    setTableLoading(true)
    let params = {
      filterInfo: filterInfoRef.current || {},
      pageInfo: pageInfoRef.current
    }
    let data: any[] = []
    let total = 0
    try {
      const res = await fetchUIListApi(params)
      total = res.totalCount || 0
      data = res.content.map((item: any) => ({ ...item, id: String(item.id) }))
    } catch (error) {
    }
    setDataSource(data)
    setTotal(total)
    setTableLoading(false)
  }, [])

  const onModalVisibleChange = useCallback(async (visible) => {
    visible && fetch()
  }, [])

  const onSearch = useCallback((params = {}) => {
    let filterInfo = filterInfoRef.current
    const { bizType, entryId, uiType, funcType, activeStatus } = filterInfo
    filterInfoRef.current = {
      ...params,
      bizType, entryId, uiType, funcType, activeStatus
    }
    fetch()
  }, [])

  const onPageChange = useCallback((beginIndex, pageSize) => {
    let newPageInfo = {
      pageSize,
      beginIndex
    }
    setPageInfo(newPageInfo)
    pageInfoRef.current = newPageInfo
    fetch()
  }, [])

  const pagination = useMemo(() => {
    const { beginIndex, pageSize } = pageInfo
    return {
      pageSizeOptions: ['50', '100', '150', '200'],
      total, // 总条数
      beginIndex,
      pageSize, // 每页显示数
      onChange: onPageChange,
    }
  }, [total, pageInfo])

  useEffect(() => {
    setValue(value)
  }, [value])

  return (
    <LoupeSelect
      {...res}
      onBlur={onBlur}
      selectorId='UISelectorId'
      value={currentValue}
      query={queryBySelect}
      edit={EditStatus.EDIT}
      labelProp={labelProp}
      valueProp={valueProp}
      onChange={onChange_}
      componentType='Input'
      viewProps={{
        title,
        viewKey: 'UISelectorProps',
        uiSchema: searchUISchema,
        schema: searchSchema,
        columns: gridSchema,
        dataSource: dataSource,
        pagination,
        loading: tableLoading,
        onSearch,
        onModalVisibleChange,
        itemState: ITEM_STATE,
        searchFormTitle: commonText.smartSearchTitleText
      }}
    />
  )
}
